from Crypto.Cipher import AES
import base64
import pandas as pd

class DataDecryptor:
    def __init__(self, secret_key):
        # 验证密钥有效性
        if len(secret_key) != 32 or not all(c in '0123456789abcdefABCDEF' for c in secret_key):
            raise ValueError("Invalid AES key (must be 32-char hex string)")
        self.secret_key = secret_key.encode('utf-8')
    
    def decrypt(self, encrypted_str):
        """解密单个字段的Base64字符串"""
        try:
            # 解码Base64
            full_data = base64.b64decode(encrypted_str)
            # 拆分组件
            nonce = full_data[:16]
            tag = full_data[16:32]
            ciphertext = full_data[32:]
            # 执行解密
            cipher = AES.new(self.secret_key, AES.MODE_EAX, nonce=nonce)
            return cipher.decrypt_and_verify(ciphertext, tag).decode('utf-8')
        except Exception as e:
            return f"<DECRYPT ERROR: {str(e)}>"

def decrypt_file(input_path, output_path, secret_key):
    """增强版文件解密函数"""
    try:
        # 读取文件（强制所有列作为字符串处理）
        df = pd.read_csv(input_path, dtype=str)
        
        # 自动识别加密列：通过数据特征判断
        encrypted_cols = []
        for col in df.columns:
            sample_value = df[col].iloc[0] if len(df) > 0 else ''
            if len(str(sample_value)) >= 44:  # Base64加密后最小长度
                try:
                    base64.b64decode(sample_value)
                    encrypted_cols.append(col)
                except:
                    continue
        
        # 执行解密
        decryptor = DataDecryptor(secret_key)
        for col in encrypted_cols:
            df[col] = df[col].apply(lambda x: decryptor.decrypt(x))
        
        # 保存结果
        df.to_csv(output_path, index=False, encoding='utf-8-sig')
        return True
    except Exception as e:
        print(f"[Critical Error] {str(e)}")
        return False